﻿' Copyright © Microsoft Corporation.  All Rights Reserved.
' This code released under the terms of the 
' Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
' <copyright file="ThumbnailDownloader.vb" company="Microsoft">
'     Copyright © Microsoft Corporation. All rights reserved.
' </copyright>
' <summary>Implements the ThumbnailDownloader class</summary>
' <author>Microsoft Expression Encoder Team</author>

Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.Windows.Threading

Namespace ExpressionMediaPlayer
	Public NotInheritable Class ThumbnailDownloader
		''' <summary>
		''' Dispatch timer for downloading thumbnails.
		''' </summary>
		Private Shared sm_timerThumbnails As DispatcherTimer
		''' <summary>
		''' queue of thumbnails to download
		''' </summary>
		Private Shared sm_downloadQueue As New Queue(Of ThumbnailImage)()
		''' <summary>
		''' create ThumbnailDownloader
		''' </summary>
		Private Sub New()
		End Sub
		''' <summary>
		''' Event handler for a Timer tick.
		''' </summary>
		''' <param name="sender">Source of the event.</param>
		''' <param name="e">Event args.</param>
		Private Shared Sub OnTimerTickThumbnailDownload(ByVal sender As Object, ByVal e As EventArgs)
			SyncLock sm_downloadQueue
				If sm_downloadQueue.Count > 0 Then
					Dim thumbnail As ThumbnailImage = sm_downloadQueue.Dequeue()
					thumbnail.LoadImage()
				End If
			End SyncLock
		End Sub
		''' <summary>
		''' Creates the timer for downloading thumbnails.
		''' </summary>
		Public Shared Sub EnableThumbnailDownload()
			If sm_timerThumbnails Is Nothing Then
				sm_timerThumbnails = New DispatcherTimer()
				sm_timerThumbnails.Interval = New TimeSpan(0, 0, 0, 0, 60) 'milliseconds - seconds - minutes - hours - days
				AddHandler sm_timerThumbnails.Tick, AddressOf OnTimerTickThumbnailDownload
			End If

			sm_timerThumbnails.Start()
		End Sub
		''' <summary>
		''' Turns off the timer for downloading thumbnails.
		''' </summary>
		Public Shared Sub DisableThumbnailDownload()
			If sm_timerThumbnails IsNot Nothing Then
				sm_timerThumbnails.Stop()
			End If
		End Sub
		''' <summary>
		''' Place a thumbnail download request in the queue.
		''' </summary>
		Public Shared Sub Enqueue(ByVal thumbnail As ThumbnailImage)
			SyncLock sm_downloadQueue
				sm_downloadQueue.Enqueue(thumbnail)
			End SyncLock
		End Sub
	End Class
End Namespace
